<template>
  <!-- BOM表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="700px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="110"
      >
        <el-row>
          <el-col :span="12"
            ><el-form-item label="BOM编号" prop="bomCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.bomCode"
                placeholder="请输入BOM编号"
                clearable
              />
              <span v-else>{{ formData.bomCode }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="BOM名称" prop="bomName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.bomName"
                placeholder="请输入BOM名称"
                clearable
              />
              <span v-else>{{ formData.bomName }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="工厂" prop="plantCode">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.plantCode"
                placeholder="请选择所在工厂"
                clearable
                style="width: 100%"
                @change="plantChange(formData.plantCode)"
                filterable
              >
                <el-option
                  v-for="item in plantList"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.organizationCode"
                />
              </el-select>

              <span v-else>{{ formData.plantCode }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="成品物料" prop="materialId">
              <select-content-input
                v-if="!props.isReadonly"
                :width="190"
                :isMultiple="false"
                :showSelectDevice="formData.materialList"
                :plantId="formData.plantId"
                :materialType="'3'"
                :disabled="formData.plantId == ''"
                @get-device="(id, object) => getDevice(id, object, $index)"
              />
              <span v-else>{{
                formData.materialCode + "-" + formData.materialName
              }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="基本数量" prop="baseQuantity">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.baseQuantity"
                placeholder="请输入基本数量"
                clearable
              />
              <span v-else>{{ formData.baseQuantity }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="数量单位" prop="baseQuantityUnit">
              <el-select
                v-model="formData.baseQuantityUnit"
                v-if="!props.isReadonly"
                placeholder="请选择数量单位"
                clearable
                disabled
              >
                <el-option
                  v-for="item in useDictionary('MeasurementUnit')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                useDictionary("MeasurementUnit", formData.baseQuantityUnit)
              }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="制造环节角色" prop="manufacturingRole">
              <el-select
                v-model="formData.manufacturingRole"
                v-if="!props.isReadonly"
                placeholder="请选择制造环节角色"
                clearable
              >
                <el-option
                  v-for="item in useDictionary('ManufacturingRole')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                useDictionary("ManufacturingRole", formData.manufacturingRole)
              }}</span>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="BOM状态" prop="bomState">
              <el-select
                v-model="formData.bomState"
                placeholder="请选择BOM状态"
                clearable
                v-if="!props.isReadonly"
              >
                <el-option
                  v-for="item in useDictionary('BOMState')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <span v-else>{{
                useDictionary("BOMState", formData.bomState)
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item></el-col
        >
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks" style="width: 700px">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
              style="width: 530px"
            />
            <span v-else>{{ formData.remarks }}</span>
          </el-form-item></el-col
        >
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
defineOptions({
  name: "MESMESBOMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  bomCode: "",
  bomName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  baseQuantity: "",
  baseQuantityUnit: "",
  manufacturingRole: "",
  bomState: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  materialList: [],
});

/** rules规则 */
const rules = reactive({
  bomCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    { required: true, message: "请输入BOM编号", trigger: "blur" },
  ],
  bomName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    { required: true, message: "请输入BOM名称", trigger: "blur" },
  ],
  materialId: [
    { required: true, message: "请输入成品物料", trigger: "change" },
  ],
  plantCode: [{ required: true, message: "请选择工厂编号", trigger: "change" }],
  baseQuantity: [
    { required: true, message: "请输入基本数量", trigger: "blur" },
  ],
  baseQuantityUnit: [
    { required: true, message: "请选择数量单位", trigger: "change" },
  ],
  manufacturingRole: [
    { required: true, message: "请选择制造环节角色", trigger: "change" },
  ],
  bomState: [{ required: true, message: "请选择BOM状态", trigger: "change" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "change" }],
});

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        formData.bomState = String(formData.bomState);
        formData.manufacturingRole = String(formData.manufacturingRole);
        formData.materialList = [
          {
            id: newVal.materialId,
            materialName: newVal.materialName,
            materialCode: newVal.materialCode,
            unit: newVal.baseQuantityUnit,
          },
        ];
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  // formRef.value.clearValidate();

  formData.id = "";
  formData.bomCode = "";
  formData.bomName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.baseQuantity = "";
  formData.baseQuantityUnit = "";
  formData.manufacturingRole = "";
  formData.bomState = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.materialList = [
    {
      id: "",
      materialName: "",
      materialCode: "",
      unit: "",
    },
  ];
}

const loading = ref(false);

/** BOM保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesbom/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};

// 当选择工厂时
const plantChange = (plantCode: string) => {
  for (let i = 0; i < plantList.value.length; i++) {
    if (plantList.value[i].organizationCode == plantCode) {
      formData.plantId = plantList.value[i].id;
    }
  }
  formData.materialList = [
    {
      id: "",
      materialName: "",
      materialCode: "",
      unit: "",
    },
  ];
};

// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any, index: number) {
  console.log(Objects[0]);
  formData.materialId = Objects[0].id;
  formData.materialCode = Objects[0].materialCode;
  formData.materialName = Objects[0].materialName;
  formData.baseQuantityUnit = Objects[0].unit;
}

onMounted(() => {
  getPlantList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

// :deep(.search-container .el-input.el-input--default.el-input--suffix) {
//   // 固定宽度
//   width: 190px !important;
// }
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
